// 权限控制
import router from '@/router'
import { getToken } from './utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router/asyncRoutes'
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = getToken()
  const whitelist = ['/login', '/404']
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/fetchUserInfo')
        // console.log(res)
        // 这里做权限控制
        // 做过滤处理
        // 如果路由的name属性能在menus权限数据中找到代表可以访问
        const menus = res.roles.menus
        // console.log(menus, asyncRoutes)
        // const filterrouter = asyncRoutes.filter(item => {
        //   return menus.includes(item.children[0].name)
        // })
        // console.log(filterrouter)
        // 老师写的
        const filterRoutes = asyncRoutes.filter(route => menus.includes(route.children[0].name))
        console.log(filterRoutes)
        // 把动态路由添加到应用的路由系统里
        router.addRoutes(filterRoutes)
        // 把动态路由数据交给菜单
        store.commit('menu/setMenuList', filterRoutes)
      }
    }
  } else {
    if (whitelist.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})
